package com.qdxwx.web.controller.h5;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.member.MemberRecordService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.models.member.MemberRecord;
import com.qdxwx.models.member.MemberRecordVO;
import com.qdxwx.models.member.MemberType;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * MemberController接口
 */
@Controller
@RequestMapping("/h5/user")
public class H5UserMemberController extends BaseController {
    @Autowired
    private MemberTypeService memberTypeService;
    @Autowired
    private MemberRecordService memberRecordService;

    /**
     * 会员
     */
    @RequestMapping("/member.html")
    public String userMember(HttpServletRequest request, ModelMap model) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return VIEW_ERROR_404;
        }
        int currentPage = TKConvert.toInteger(request.getParameter("page"), 1);
        PageRequest page = new PageRequest(currentPage, 10);

        /*查询开通会员的记录*/
        MemberRecord query = new MemberRecord();
        query.setUserId(user.getUserId());
        List<MemberRecordVO> orderDetails = memberRecordService.getVOList(query, page);
        long total = memberRecordService.count(query);

        model.put("totalPages", page.getTotalPages(total));

        /*会员类型*/
        List<MemberType> memberTypeList = memberTypeService.getList();
        if (ObjectUtils.isNotNull(memberTypeList)) {
            for (MemberType memberType : memberTypeList) {
                /*如果有会员*/
                /*查询所有会员类型当前时间的开通情况*/
                /*给拥有的会员类型set endTime*/
                MemberRecord memberRecord = memberRecordService.getByUserId(user.getUserId(), memberType.getId());
                if (memberRecord != null) {
                    memberType.setEndDate(memberRecord.getEndDate());
                }
            }
        }
        model.put("memberTypeList", memberTypeList);
        model.put("user", user);
        model.put("memberDetails", orderDetails);
        model.put("page", page);
        return getViewPathH5("user/uc-member");
    }

}